package com.zx.deploy.service.impl;

import com.zx.deploy.common.exception.BusinessException;
import com.zx.deploy.common.utils.FileMD5Util;
import com.zx.deploy.common.utils.FileUtil;
import com.zx.deploy.common.utils.RSAUtil;
import com.zx.deploy.config.DeployConfig;
import com.zx.deploy.service.UploadService;
import org.apache.commons.io.FileUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ClassPathResource;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.URISyntaxException;

/**
 * 上传下载操作
 * @author jbyu
 *
 */
@Service
public class UploadServiceImpl implements UploadService {

    @Autowired
    private DeployConfig deployConfig;

    @Override
    public void upload(MultipartFile file) throws IOException, URISyntaxException {
        byte[] headBytes = new byte[172];
        InputStream inputStream = file.getInputStream();
        inputStream.read(headBytes);
        String headerEn = new String(headBytes,"utf-8");
        String headerDe = "";
        try {
            headerDe = RSAUtil.decrypt(headerEn);
        } catch (Exception e) {
            e.printStackTrace();
            throw new BusinessException("不是符合要求的升级包");
        }
        String[] tmps = headerDe.split("\\|");
        String md5 = tmps[0].replace("md5:","");
        String version = tmps[1].replace("version:","");
        ByteArrayOutputStream byteOutputStream = new ByteArrayOutputStream();
        byte[] bytes = new byte[inputStream.available()];
        int length;
        while((length = inputStream.read(bytes)) != -1){
            byteOutputStream.write(bytes,0,length);
        }
        String calcMd5 = FileMD5Util.getMD5ByByte(byteOutputStream.toByteArray());
        if(!calcMd5.equals(md5)){
            throw new BusinessException("文件损坏或被篡改");
        }
        File versionFile = FileUtil.getFile("current-version.txt");
        String currentVersion =  FileUtils.readFileToString(versionFile,"UTF-8");
        if((!StringUtils.isEmpty(currentVersion)) && Long.parseLong(currentVersion)>=Long.parseLong(version)){
            throw new BusinessException("上传版本不能低于或等于当前版本");
        }

        File destFile = new File( deployConfig.soft_file_path + File.separator + deployConfig.soft_package_name);
        FileUtils.writeByteArrayToFile(destFile,byteOutputStream.toByteArray());
        File tmpVersionFile = FileUtil.getFile("tmp-version.txt");
        FileUtils.writeByteArrayToFile(tmpVersionFile,version.getBytes("UTF-8"));
    }
}
